//
//  SLPermissionSetVC.m
//  SlockApp
//
//  Created by 凯朱 on 2024/7/25.
//

#import "SLAccessManagerVC.h"
#import "SLAccessManagerView.h"
#import "SLUnlockAlertView.h"
#import "SLLockLogVC.h"
#import "SLAccessSettingVC.h"
#import "SLDeviceSettingVC.h"
#import "SLSelectAccessTypeVC.h"

@interface SLAccessManagerVC (){
    BOOL _isLoadSuccess;
    BOOL _isFirstLoad;
}
@property (nonatomic, strong)UITableView *tableView;
@property (nonatomic, strong)SLAccessManagerView *headView;
@property (nonatomic, strong)SLLockKeyModel *addKeyModel;
@end

@implementation SLAccessManagerVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpSubViews];
    _isFirstLoad = YES;
    [ZCTool showLoadingOnKeyWindow];
    [self loadKeyDatas:NO];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(addAccessSuccess:) name:@"kAddAccessSuccess" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshList) name:@"kRefreshKeyData" object:nil];
}


-(void)refreshList{
    [ZCTool showLoadingOnKeyWindow];
    [self loadKeyDatas:NO];
}

-(void)backBtnClicked{
    [super backBtnClicked];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)loadKeyDatas:(BOOL)isSync{
    kWeakSelf(self);
    _isLoadSuccess = NO;
    NSDictionary *params = @{@"deviceId":kCurClickDevice.deviceId,
                             @"page":@"1",
                             @"pageSize":@"999"};
    NSMutableArray *dataArray = [NSMutableArray new];
    [ZKHttpManager getWithPath:@"/msl_lock_key/list" params:params finished:^(BOOL isSuccessed, id  _Nonnull result, NSString * _Nonnull code, NSString * _Nonnull message) {
        [ZCTool hideLoadingOnKeyWindow];
        [self->_headView stopRefreshAnimation];
        if (!isSuccessed) {
            weakself.addKeyModel = nil;
            kShowToast(message);
            return;
        }
        if (isSync) {
            kShowToast(@"Refresh success!");
        }
        self->_isLoadSuccess = YES;
        NSArray *data = [[NSArray alloc] initWithArray:result[@"result"][@"items"]];
        //更新数据源
        [data enumerateObjectsUsingBlock:^(NSDictionary *dict, NSUInteger idx, BOOL * _Nonnull stop) {
            SLLockKeyModel *model = [SLLockKeyModel modelWithDictionary:dict];
            model.weekDays = [ZCTool arrayWithJsonStr:dict[@"weekDays"]];
            if (model.keyType  == 2){
                if (model.weekDays.count > 0) {
                    NSString *startDate = [NSString convertDateString:model.startTime outFormart:@"dd MMM"];
                    NSString *endDate = [NSString convertDateString:model.endTime outFormart:@"dd MMM"];
                    model.desc = [NSString stringWithFormat:@"%@ ~ %@ (%@)",startDate,endDate,kLocalString(@"Time repeat")];
                }else{
                    NSString *startTime = [NSString convertDateString:model.startTime outFormart:@"dd MMM. HH:mm"];
                    NSString *endTime = [NSString convertDateString:model.endTime outFormart:@"dd MMM. HH:mm"];
                    model.desc = [NSString stringWithFormat:@"%@ ~ %@",startTime,endTime];
                }
                
            }else if(model.keyType  == 3){
                NSString *startTime = [NSString convertDateString:model.startTime outFormart:@"dd MMM. HH:mm"];
                NSString *endTime = [NSString convertDateString:model.endTime outFormart:@"dd MMM. HH:mm"];
                model.desc = [NSString stringWithFormat:@"%@ ~ %@",startTime,endTime];
            }
            if ([kSTRING(model.isUsbKey) isEqualToString:@"1"] && model.keyName.length == 0) {
                model.keyName = kLocalString(@"Usb key");
            }
            
            [dataArray addObject:model];
        }];
        NSArray *newData = [self sortWithTime:dataArray];
        self->_model.keys = newData;
        [self->_headView refreshSubViewWith:self->_model];
        
        //添加指纹钥匙自动跳转逻辑
        if (weakself.addKeyModel) {
            NSString *keyId = weakself.addKeyModel.keyId;
            weakself.addKeyModel = nil;
            [newData enumerateObjectsUsingBlock:^(SLLockKeyModel *keyModel, NSUInteger idx, BOOL * _Nonnull stop) {
                if ([keyModel.keyId isEqualToString:keyId]) {
                    [self pushKeySetVc:keyModel isAddBlueToothKey:YES];
                    *stop = YES;
                }
            }];
        }
        if (self->_isFirstLoad) {
            self->_isFirstLoad = NO;
            __block BOOL isHaveOneTimeFinger = NO;
            [dataArray enumerateObjectsUsingBlock:^(SLLockKeyModel *keyModel, NSUInteger idx, BOOL * _Nonnull stop) {
                if (keyModel.lockType == 1 && keyModel.keyType == 3) {
                    isHaveOneTimeFinger = YES;
                    *stop = YES;
                }
            }];
            //有一次性指纹钥匙才每次去自动同步数据
//            if (isHaveOneTimeFinger) {
//                [self updateKeyDatasBackground];
//            }
        }
    }];
}

-(NSArray *)sortWithTime:(NSArray *)dataArray{
    // 使用 NSSortDescriptor 进行排序
    NSArray *sortedArray = [dataArray sortedArrayUsingComparator:^NSComparisonResult(SLLockKeyModel *model1, SLLockKeyModel *model2) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
        NSDate *date1 = [dateFormatter dateFromString:model1.createTime];
        NSDate *date2 = [dateFormatter dateFromString:model2.createTime];
        return [date2 compare:date1]; // 最新的在前面
    }];
    return sortedArray;
}

-(void)setUpSubViews{
    self.title = _model.deviceName;
    
    [self.view addSubview:self.tableView];
    _headView = [SLAccessManagerView viewFromXIB];
    _headView.frame = self.tableView.bounds;
    [self refreshHeadView];
    kWeakSelf(self);
    [_headView setBtnBlock:^(NSInteger index) {
        [weakself handleSetView:index];
    }];
    [_headView setHeightChangeBlock:^(CGFloat height) {
        weakself.headView.height = height+300;
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            weakself.tableView.tableHeaderView = weakself.headView;
            [weakself.tableView layoutIfNeeded];
        });
    }];
    [_headView setCellCilckBlock:^(SLLockKeyModel * _Nonnull model) {
        [weakself handleCellClickAction:model];
    }];
    
    _tableView.tableHeaderView = _headView;
    
    UIButton *addBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [addBtn setImage:[UIImage imageNamed:@"icon_access_add"] forState:UIControlStateNormal];
    addBtn.frame = CGRectMake(kScreenWidth/2-32, kScreenHeight-SafeAreaBottomHeight-30-64, 64, 64);
    [self.view addSubview:addBtn];
    [addBtn addTarget:self action:@selector(addAccessAction) forControlEvents:UIControlEventTouchUpInside];
}

-(void)refreshHeadView{
    NSString *time = [[NSUserDefaults standardUserDefaults] objectForKey:@"kLastRefreshKeyDatasTime"];
    _headView.topLbl2.text = kReplace(time, @"--");
}

-(void)settingAction{
    SLDeviceSettingVC *vc = [[SLDeviceSettingVC alloc] init];
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)addAccessAction{
    if (!_isLoadSuccess) {
        kShowToast(@"Load data faild");
        [ZCTool showLoadingOnKeyWindow];
        [self loadKeyDatas:NO];
        return;
    }
    //指纹钥匙
    SLSelectAccessTypeVC *vc = [[SLSelectAccessTypeVC alloc] init];
    SLLockKeyModel *model = [SLLockKeyModel new];
    if (_headView.curBtn == _headView.leftBtn) {
        model.lockType = 1;
    }else{//蓝牙钥匙
        model.lockType = 2;
    }
    //计算成员Id
    model.uid = [self calculateMissingUID];
    vc.keyModel = model;
    [self.navigationController pushViewController:vc animated:YES];
}

-(NSString *)calculateMissingUID {
    // 创建一个可变的集合来存储现有的 UID
    NSMutableSet<NSString *> *existingUIDs = [NSMutableSet set];
    // 遍历模型的 keys，收集现有的 UID
    [_model.keys enumerateObjectsUsingBlock:^(SLLockKeyModel * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [existingUIDs addObject:obj.uid];
    }];
    // 遍历 1 到 100 的范围，查找未存在的 UID
    for (NSInteger i = 1; i <= 100; i++) {
        NSString *uid = [NSString stringWithFormat:@"%ld", (long)i];
        NSLog(@"uid = %@",uid);
        if (![existingUIDs containsObject:uid]) {
            return uid; // 返回第一个缺失的 UID
        }
    }
    return nil; // 如果所有 UID 都存在，则返回 nil
}

-(void)addAccessSuccess:(NSNotification *)notify{
    _addKeyModel = notify.object[@"model"];
    [ZCTool showLoadingOnKeyWindow];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self loadKeyDatas:NO];
    });
}

-(void)pushKeySetVc:(SLLockKeyModel *)keyModel isAddBlueToothKey:(BOOL)isAddBlueToothKey{
    SLAccessSettingVC *vc = [[SLAccessSettingVC alloc] init];
    vc.keyModel = keyModel;
    vc.isAddBlueToothKey = isAddBlueToothKey;
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -
#pragma mark - ================<同步钥匙数据>===============
-(void)handleSetView:(NSInteger )index{
    if (index == 1) {//同步钥匙数据
        [_headView startRefreshAnimation];
        [self updateKeyDatas:YES];
    }
}

-(void)updateKeyDatasBackground{
    
    [ZCTool connectDeviceBackgroundWith:kCurClickDevice finish:^(BOOL isSuccess) {
        if (!isSuccess) {
            return;
        }
        [self->_headView startRefreshAnimation];
        [ZCTool batchSyncDeviceKeyDatas:^(BOOL isSuccess,NSString *message) {
            if (!isSuccess) {
                [self->_headView stopRefreshAnimation];
                return;
            }
            NSString *time = [ZCTool getCurDateStr];
            [[NSUserDefaults standardUserDefaults] setObject:time forKey:@"kLastRefreshKeyDatasTime"];
            [self refreshHeadView];
            [self loadKeyDatas:NO];
        }];
    }];
}

-(void)updateKeyDatas:(BOOL)isSync{
    
    [ZCTool connectDeviceWith:kCurClickDevice toast:kLocalString(@"Connecting...") finish:^(BOOL isSuccess) {
        if (!isSuccess) {
            if (isSync) {
                [self->_headView stopRefreshAnimation];
            }else{
                [self loadKeyDatas:NO];
            }
            return;
        }
        
        [ZCTool batchSyncDeviceKeyDatas:^(BOOL isSuccess,NSString *message) {
            if (!isSuccess) {
                if (isSync) {
                    [self->_headView stopRefreshAnimation];
                    kShowToast(message);
                }else{
                    [self loadKeyDatas:NO];
                }
                return;
            }
            NSString *time = [ZCTool getCurDateStr];
            [[NSUserDefaults standardUserDefaults] setObject:time forKey:@"kLastRefreshKeyDatasTime"];
            [self refreshHeadView];
            [self loadKeyDatas:isSync];
        }];
    }];
}

-(void)handleCellClickAction:(SLLockKeyModel *)model{
    [self pushKeySetVc:model isAddBlueToothKey:NO];
}

#pragma mark - ================<懒加载>===============
-(UITableView *)tableView{
    if (_tableView == nil) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight,kScreenWidth,kScreenHeight-SafeAreaTopHeight-SafeAreaBottomHeight-64-30-15) style:UITableViewStyleGrouped];
        _tableView.backgroundColor = KClearColor;
    }
    return _tableView;
}


@end
